/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.crane.webtemplate;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author CraneLeeon
 */
public class SecurityFilter implements Filter {

    private static final boolean debug = true;
    private static final Log log = LogFactory.getLog(SecurityFilter.class);

    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;

    public SecurityFilter() {
    } 

    

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {
        String json = null;
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
	try {
            HttpSession session = req.getSession();
            if(session.getAttribute("user") == null){
                json = new JSONObject()
                       .put("success", false)
                       .put("err_code", Tokens.ERR_USER_NOT_AUTHORIZED)
                       .put("info", "Not authorized to access")
                       .toString();
                res.setStatus(res.SC_FORBIDDEN);
                writeRes(json, res);
                return;
            }
	}catch(Throwable t) {
            try {
                json = new JSONObject()
                        .put("success", false)
                        .put("err_code", Tokens.ERR_UNKNOWN)
                        .put("info", t)
                        .toString();
            } catch (JSONException ex) {
                log.debug(ex);
            }
	    log.debug(t);
            writeRes(json, res);
	}
        chain.doFilter(request, response);
	
    }

    public void writeRes(String json, HttpServletResponse res) throws IOException{
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/JSON");
        res.getWriter().print(json);
        res.getWriter().flush();
        res.getWriter().close();
    }
    
    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
	return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
	this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     */
    public void destroy() { 
    }

    /**
     * Init method for this filter 
     */
    public void init(FilterConfig filterConfig) { 
	this.filterConfig = filterConfig;
	
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
	if (filterConfig == null) return ("SecurityFilter()");
	StringBuffer sb = new StringBuffer("SecurityFilter(");
	sb.append(filterConfig);
	sb.append(")");
	return (sb.toString());
    }

    

}
